

#import "BCNSpcWERule2.h"

@implementation BCNSpcWERule2

-(void) initWithSide: (SpcControlSide) side Limit:(SpcControlLimit*) limit
{
	pointCount = 2;
	controlSide = side;
	
	[limit retain];
  [controlLimit release];
  controlLimit = limit;
}
	// return rule type
	-(BCNSpcRuleType) RuleType
	{
	    return BCNSpcRuleType.WERule2;
	}
	
	// return rule point count
	-(int) GetRulePointCount
	{
	    return PointCount;
	}
	
	// add point
	//true if data is violated the rule, others false.
	-(bool) AddPoint(double data)
	{
	    [dataQueue enqueue:data];
	    BOOL rlt = [self violate];
	    
	    if (rlt)
	        Reset();
	    
	    return rlt;
	}
	
	
	// add point with sample size
	// limits for data point will be calculated with sample size.
	// true if data is violated the rule, others false
	-(BOOL)AddPoint:(double) data size:(double) sampleSize
	{
		if (sampleSize < 0) 
		return NO;
		
		// calculate new limit for given new sample size.
		[controlLimit Calculate: (int)sampleSize];
		return [self AddPoint: data];
	}
	
	        
	        // reset the rule.
	        // clear the queue in rule instance.
	        -(void) Reset()
	        {
	            _queue.Clear();
	        }
	
	// private functions
	// travel through the queue to check.
	-(bool) violate()
	{
	    int above = 0;
	    int below = 0;
	    for(double d in _queue)
	    {
	        if (d > _limit.UWL)
	            above++;
	
	        if (d < _limit.LWL)
	            below++;
	    }
	
	    switch (_side)
	    {
	        case BCNSpcControlSide.Upper:
	            if (above >= ViolateCount)
	                return YES;
	            break;
	        case BCNSpcControlSide.Lower:
	            if (below >= ViolateCount)
	                return YES;
	            break;
	        case BCNSpcControlSide.Both:
	            if (above >= ViolateCount || below >= ViolateCount)
	                return YES;
	            break;
	    }
	    return NO;
	}

-(void) dealloc
{
  [controlLimit release];
  [super dealloc];
}

@end // BCNSpcWERule2